package com.ktjy.web;

import com.ktjy.entity.Auction;
import com.ktjy.entity.Auctionrecord;
import com.ktjy.entity.Auctionuser;
import com.ktjy.service.AuctionrecordService;
import com.ktjy.service.impl.AuctionrecordServiceImpl;
import my.framework.anno.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: DABINGCHNEGJIAO
 * @CreateTime: 2025-06-17
 * @Description:
 * @Version: 1.0
 */
public class AuctionrecordControll {
    AuctionrecordService auctionrecordService = new AuctionrecordServiceImpl();

    //查询拍卖品关联记录
    @RequestMapping("/findAuctionrdById")
    public String AuctionrecordControll(HttpServletRequest req, HttpServletResponse resp) {
        String auctionId = req.getParameter("auctionId");
        try {
            List<Auctionrecord> auctionrecords = auctionrecordService.selectAuctionrecordById(Long.valueOf(auctionId));
            // 获取关联的拍卖品信息（从第一条记录中获取）
            Auction auction = auctionrecords.get(0).getAuction();
            req.getSession().setAttribute("auction", auction);
            if (auctionrecords != null) {
                // 将拍卖品关联记录存入会话中
                req.getSession().setAttribute("auctionrecords", auctionrecords);
                return "redirect:/Number.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/do/page";
    }

    //新增拍卖品关联记录
    @RequestMapping("/insertAuctionrecord")
    public String insertAuctionrecord(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        Auction auction = (Auction) session.getAttribute("auction"); //竞拍的商品信息
        Auctionuser auctionuser = (Auctionuser) session.getAttribute("auctionuser"); //登录的用户信息
        String auctionId = auction.getAuctionId().toString();
        session.removeAttribute("errorMsg");
        // 检查拍卖是否已结束
        if (auction != null) {
            //获取结束时间
            String auctionEndTimeStr = auction.getAuctionEndTime();
            //开始时间
            String auctionStartTime = auction.getAuctionStartTime();
            // 解析结束时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 使用Instant进行更精确的比较
            Instant now = Instant.now();
            Instant endTime = LocalDateTime.parse(auctionEndTimeStr, formatter)
                    .atZone(ZoneId.systemDefault())
                    .toInstant();
            Instant endTime2 = LocalDateTime.parse(auctionStartTime, formatter)
                    .atZone(ZoneId.systemDefault())
                    .toInstant();
            if (now.isBefore(endTime2)) {
                session.setAttribute("errorMsg", "拍卖未开始，无法竞拍");
                return "forward:/do/findAuctionrdById?auctionId=" + auctionId;
            }
            if (now.isAfter(endTime)) {
                session.setAttribute("errorMsg", "拍卖已结束，无法竞拍");
                return "forward:/do/findAuctionrdById?auctionId=" + auctionId;
            }
        }

        String userId = auctionuser.getUserId().toString();
        String auctionPrice = req.getParameter("auctionPrice");
        String data = req.getParameter("auctionTime");
        String auctionTime = convertToMySQLString(data);
        Auctionrecord auctionrecord = new Auctionrecord();
        auctionrecord.setAuctionId(Long.valueOf(auctionId));
        auctionrecord.setUserId(Long.valueOf(userId));
        auctionrecord.setAuctionPrice(Double.valueOf(auctionPrice));
        auctionrecord.setAuctionTime(auctionTime);
        boolean result = auctionrecordService.insertAuctionrecord(auctionrecord);
        return "forward:/do/findAuctionrdById?auctionId=" + auctionId;

    }


    //查询每个拍卖品的所有拍卖品记录 每个拍卖品记录里面有用户信息
    @RequestMapping("/findAuctionrecordAll")
    public String findAuctionrecordAll(HttpServletRequest req, HttpServletResponse resp) {

        List<Auction> auctionrecordStart = auctionrecordService.selectAuctionrecordAll("start"); //拍卖中的商品
        List<Auction> auctionrecordEnd = auctionrecordService.selectAuctionrecordAll("end"); //拍卖结束的商品
        Map<String, Double> StartUser = findA(auctionrecordStart, 3);//拍卖中的商品中 出价记录的用户信息
        Map<String, Double> StartEnd = findA(auctionrecordEnd, 1);//拍卖结束的商品中 买家的用户信息
        req.setAttribute("auctionrecordStart", auctionrecordStart);
        req.setAttribute("auctionrecordEnd", auctionrecordEnd);
        req.setAttribute("StartUser", StartUser);
        req.setAttribute("EndUser", StartEnd);
        return "forward:/auctionResult.jsp";
    }

    // 转换为 MySQL 格式字符串 (yyyy-MM-dd HH:mm:ss)
    public static String convertToMySQLString(String isoDate) {
        Instant instant = Instant.parse(isoDate);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    //查询每个拍卖品的所有拍卖品记录 每个拍卖品记录里面有用户信息
    public Map<String, Double> findA(List<Auction> auctions, Integer statusorEnd) {
        Map<String, Double> userMaxBidMaps = new HashMap<String, Double>();
        for (Auction auction : auctions) {
            // 1. 按用户分组，保留每个用户的最高出价
            Map<String, Auctionrecord> userMaxBidMap = auction.getAuctionrecordList().stream()
                    .collect(Collectors.toMap(
                            record -> record.getUser().getUserName(),
                            Function.identity(),
                            (existing, replacement) ->
                                    existing.getAuctionPrice() > replacement.getAuctionPrice() ? existing : replacement
                    ));

            // 2. 获取出价最高的前三位用户
            List<Auctionrecord> topRecord = userMaxBidMap.values().stream()
                    .sorted((r1, r2) -> Double.compare(r2.getAuctionPrice(), r1.getAuctionPrice()))
                    .limit(statusorEnd)
                    .collect(Collectors.toList());
            for (Auctionrecord auctionrecord : topRecord) {
                userMaxBidMaps.put(auctionrecord.getUser().getUserName(), auctionrecord.getAuctionPrice());
            }

        }
        return userMaxBidMaps;
    }

}
